{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "# Endpoint layer pattern\n",
    "\n",
    "**Author:** [fchollet](https://twitter.com/fchollet)<br>\n",
    "**Date created:** 2019/05/10<br>\n",
    "**Last modified:** 2019/05/10<br>\n",
    "**Description:** Demonstration of the \"endpoint layer\" pattern (layer that handles loss management)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Setup\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "import numpy as np\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Usage of endpoint layers in the Functional API\n",
    "\n",
    "An \"endpoint layer\" has access to the model's targets, and creates arbitrary losses and\n",
    "metrics using `add_loss` and `add_metric`. This enables you to define losses and\n",
    " metrics that don't match the usual signature `fn(y_true, y_pred, sample_weight=None)`.\n",
    "\n",
    "Note that you could have separate metrics for training and eval with this pattern.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "\n",
    "class LogisticEndpoint(keras.layers.Layer):\n",
    "    def __init__(self, name=None):\n",
    "        super(LogisticEndpoint, self).__init__(name=name)\n",
    "        self.loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)\n",
    "        self.accuracy_fn = keras.metrics.BinaryAccuracy(name=\"accuracy\")\n",
    "\n",
    "    def call(self, logits, targets=None, sample_weight=None):\n",
    "        if targets is not None:\n",
    "            # Compute the training-time loss value and add it\n",
    "            # to the layer using `self.add_loss()`.\n",
    "            loss = self.loss_fn(targets, logits, sample_weight)\n",
    "            self.add_loss(loss)\n",
    "\n",
    "            # Log the accuracy as a metric (we could log arbitrary metrics,\n",
    "            # including different metrics for training and inference.\n",
    "            self.add_metric(self.accuracy_fn(targets, logits, sample_weight))\n",
    "\n",
    "        # Return the inference-time prediction tensor (for `.predict()`).\n",
    "        return tf.nn.softmax(logits)\n",
    "\n",
    "\n",
    "inputs = keras.Input((764,), name=\"inputs\")\n",
    "logits = keras.layers.Dense(1)(inputs)\n",
    "targets = keras.Input((1,), name=\"targets\")\n",
    "sample_weight = keras.Input((1,), name=\"sample_weight\")\n",
    "preds = LogisticEndpoint()(logits, targets, sample_weight)\n",
    "model = keras.Model([inputs, targets, sample_weight], preds)\n",
    "\n",
    "data = {\n",
    "    \"inputs\": np.random.random((1000, 764)),\n",
    "    \"targets\": np.random.random((1000, 1)),\n",
    "    \"sample_weight\": np.random.random((1000, 1)),\n",
    "}\n",
    "\n",
    "model.compile(keras.optimizers.Adam(1e-3))\n",
    "model.fit(data, epochs=2)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Exporting an inference-only model\n",
    "\n",
    "Simply don't include `targets` in the model. The weights stay the same.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "inputs = keras.Input((764,), name=\"inputs\")\n",
    "logits = keras.layers.Dense(1)(inputs)\n",
    "preds = LogisticEndpoint()(logits, targets=None, sample_weight=None)\n",
    "inference_model = keras.Model(inputs, preds)\n",
    "\n",
    "inference_model.set_weights(model.get_weights())\n",
    "\n",
    "preds = inference_model.predict(np.random.random((1000, 764)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text"
   },
   "source": [
    "## Usage of loss endpoint layers in subclassed models\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 0,
   "metadata": {
    "colab_type": "code"
   },
   "outputs": [],
   "source": [
    "\n",
    "class LogReg(keras.Model):\n",
    "    def __init__(self):\n",
    "        super(LogReg, self).__init__()\n",
    "        self.dense = keras.layers.Dense(1)\n",
    "        self.logistic_endpoint = LogisticEndpoint()\n",
    "\n",
    "    def call(self, inputs):\n",
    "        # Note that all inputs should be in the first argument\n",
    "        # since we want to be able to call `model.fit(inputs)`.\n",
    "        logits = self.dense(inputs[\"inputs\"])\n",
    "        preds = self.logistic_endpoint(\n",
    "            logits=logits,\n",
    "            targets=inputs[\"targets\"],\n",
    "            sample_weight=inputs[\"sample_weight\"],\n",
    "        )\n",
    "        return preds\n",
    "\n",
    "\n",
    "model = LogReg()\n",
    "data = {\n",
    "    \"inputs\": np.random.random((1000, 764)),\n",
    "    \"targets\": np.random.random((1000, 1)),\n",
    "    \"sample_weight\": np.random.random((1000, 1)),\n",
    "}\n",
    "\n",
    "model.compile(keras.optimizers.Adam(1e-3))\n",
    "model.fit(data, epochs=2)\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "endpoint_layer_pattern",
   "private_outputs": false,
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}